﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Office.Interop.Excel;

namespace WFL.Office.Excel
{
    public class ExcelApplication : DisposableSite
    {
        private readonly object _lock = new object();

        public int SheetsInNewWorkbook
        {
            get { return _application.SheetsInNewWorkbook; }
            set { _application.SheetsInNewWorkbook = value; }
        }

        private ExcelWorkbooks _workbooks;
        public ExcelWorkbooks Workbooks
        {
            get
            {
                if (_workbooks == null)
                {
                    lock (_lock) { if (_workbooks == null) { _workbooks = new ExcelWorkbooks(_application.Workbooks) { Application = this }; } }
                }
                return _workbooks;
            }
        }

        private Application _application;

        public ExcelApplication()
        {
            _application = new ApplicationClass();
            _application.AlertBeforeOverwriting = false;
            _application.DisplayAlerts = false;
            _application.Visible = false;
            _application.SheetsInNewWorkbook = 1;
        }

        protected override void Dispose(bool disposing)
        {
            if (_application != null)
            {
                if (disposing)
                {
                    ExcelWorkbooks workbooks = _workbooks;
                    if (workbooks != null)
                    {
                        _workbooks = null;
                        workbooks.Dispose();
                    }
                    _application.Quit();
                    Marshal.ReleaseComObject(_application);
                }
                _application = null;
                base.Dispose(disposing);
            }
        }
    }
}
